package cc.dowell.controller;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.HashMap;

@Slf4j
@RestController
@RequestMapping("/detect")
public class DetectController {


    @Value("${ext-service.ai-fruit}")
    String aiFruitServiceURL;

    @Value("${custom-setting.file-path.root}")
    private String rootPath;

    @Value("${custom-setting.file-path.img-upload}")
    String imgUploadPath;


    @GetMapping
    public Object detect(@RequestParam String filename) {

        //上传图片的保存路径
        String savePath = rootPath + imgUploadPath;
        //BufferedInputStream in = FileUtil.getInputStream(savePath + filename);
        //byte[] fileBytes = IoUtil.readBytes(in);  //读取图片文件流，并自动关闭

        File imgFile = new File(savePath + filename);

        //开始计时
        long s1 = System.currentTimeMillis();
        log.info("本次AI请求开始计时");
        //利用Hutool转Base64
        // String encodeBase64 = Base64.encode(fileBytes);

        //表单数据
        HashMap<String, Object> formDataMap = new HashMap<>();
        formDataMap.put("imgFile", imgFile);
        // paramMap.put("image", encodeBase64);
        //压缩图片

        //10秒超时
        // application/octet-stream
        // 二进制数据放入请求体用 .body(byte[])
        HttpResponse response = HttpRequest.post(aiFruitServiceURL)
                .header(Header.CONTENT_TYPE, "multipart/form-data")
                .header(Header.ACCEPT_CHARSET, "utf-8")
                .form(formDataMap)
                .timeout(10 * 1000)
                .execute();

        String result = response.body();
        //开始计时
        long s2 = System.currentTimeMillis();
        long t = s2 - s1;
        log.info("本次AI请求耗时：{}", t);
        return result;
    }


}
